import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, message, Rate } from 'antd';
import 'moment/locale/zh-cn';
import { TableC, FirstHeaderC, SecondHeaderC } from '../../../../components';
import styles from './index.less';
import colors from '../../../../css/colors';

@connect(({ monitorpublicopinionM, userM: user, globalM, loading }) => ({
  monitorpublicopinionM,
  user,
  globalM,
  loading,
}))
export default class DetailC extends PureComponent {
  state = {
    publicSentiment: {},
  };

  componentDidMount() {
    const obj = JSON.parse(sessionStorage.getItem('publicSentiment'));
    if (!obj) {
      message.warning('未获取到详情信息');
      this.props.dispatch({
        type: 'tabController/closeTab',
        payload: {
          newUrl: '/marketAnalysis/Monitorpublicopinion',
        },
      });
      return;
    }
    this.setState(
      {
        publicSentiment: obj, // 保存至state里
      },
      () => {
        sessionStorage.removeItem('publicSentiment');
        if (this.props.type == 'news') {
          this.querNewsDetail(); // 查询新闻详情
        }
        this.queryHoldList(); // 查询持仓相关
      },
    );
  }

  componentDidUpdate(prevProps, prevState) {
    const obj = JSON.parse(sessionStorage.getItem('publicSentiment'));
    if (obj && obj.type == this.props.type) {
      // 判断是新闻还是公告 之后 再比对数据是否相同
      if (JSON.stringify(prevState.publicSentiment) !== JSON.stringify(obj)) {
        this.setState(
          {
            publicSentiment: obj, // 保存至state里
          },
          () => {
            sessionStorage.removeItem('publicSentiment');
            if (this.props.type == 'news') {
              this.querNewsDetail(); // 查询新闻详情
            }
            this.queryHoldList(); // 查询持仓相关
          },
        );
      }
    }
  }

  componentWillUnmount() {
    // 离开前清除models数据
    if (this.props.type == 'notice') {
      // 关闭后去除notice缓存
      sessionStorage.removeItem('noticeInfo');
      this.props.dispatch({
        type: 'monitorpublicopinionM/setState',
        payload: {
          noticeHoldColumns: undefined, // notice相关持仓表头
          noticeHoldData: undefined, // notice相关持仓数据
        },
      });
    } else {
      this.props.dispatch({
        type: 'monitorpublicopinionM/setState',
        payload: {
          newsInfo: {}, // 新闻详情
          newsHoldColumns: undefined, // news相关持仓表头
          newsHoldData: undefined, // news相关持仓数据
        },
      });
    }
  }

  // 查询新闻详情
  querNewsDetail = () => {
    const { publicSentiment } = this.state;
    this.props.dispatch({
      type: 'monitorpublicopinionM/comNewsDetail',
      payload: {
        id: publicSentiment.bondID,
      },
    });
  };

  // 查询持仓数据
  queryHoldList = () => {
    const {
      user: { currentUser },
      dispatch,
      type,
    } = this.props;
    const { publicSentiment } = this.state;
    dispatch({
      type: 'monitorpublicopinionM/comAssociatedPosition',
      payload: {
        userId: currentUser.userId,
        comId: publicSentiment.comid,
        type,
      },
    });
  };

  // 展示表格
  showTable = () => {
    const {
      monitorpublicopinionM: { newsHoldData, newsHoldColumns, noticeHoldColumns, noticeHoldData },
      type,
    } = this.props;
    const currentHeight = document.getElementById('tabDiyWidth') ? document.getElementById('tabDiyWidth').offsetHeight - 185 : 0;
    const columns = type == 'news' ? newsHoldColumns : noticeHoldColumns;
    const dataSource = type == 'news' ? newsHoldData : noticeHoldData;
    columns &&
      columns.map((item) => {
        if (item.key != 'proudctName') {
          item.width = '33.33%';
        }
      });

    return <TableC columns={columns} dataSource={dataSource} hidePage={true} scroll={{ x: '100%', y: currentHeight ? currentHeight : 300 }} rowKey={'key'} />;
  };

  showValue = (arr, value) => {
    if (!arr.length) return '--';
    let text = '';
    arr.forEach((item) => {
      if (item.code === value) text = item.value;
    });
    return text || '--';
  };

  // 展示详情
  showInfo = () => {
    const {
      monitorpublicopinionM: { newsInfo },
      type,
    } = this.props;
    const {
      globalM: {
        dataDictionary: { COMPANY_IMPORTANCE = [], COMPANY_AFFECTION = [] },
      },
    } = this.props;
    let info = {};
    if (type == 'news') {
      info = newsInfo;
    } else {
      info = JSON.parse(sessionStorage.getItem('noticeInfo')) || {};
    }
    const currentHeight = document.getElementById('tabDiyWidth') ? document.getElementById('tabDiyWidth').offsetHeight - 180 : 0;
    const text = info.affection ? this.showValue(COMPANY_AFFECTION, info.affection) : '';
    const color1 = text == '正面' ? colors.debtAndProfit.text[0] : text == '负面' ? colors.debtAndProfit.text[1] : colors.debtAndProfit.text[3];
    const styleAffect = {
      color: color1,
      display: 'inline-block',
      border: ` 1px solid ${color1}`,
      background: text == '正面' ? colors.debtAndProfit.area[0] : text == '负面' ? colors.debtAndProfit.area[1] : 'transparent',
      padding: ' 0 6px',
      height: '20px',
      lineHeight: '20px',
      marginRight: '20px',
    };
    return type == 'news' ? (
      <div className={newsInfo} style={{ maxHeight: currentHeight, overflow: 'auto' }}>
        <div style={{ marginBottom: '5px' }}>
          <span style={text ? styleAffect : {}}>{text}</span>
          <b>{info.title || '-'}</b>
        </div>
        <div>
          <p>
            <span>日期:</span>
            <span>{info.dateTime || '-'} </span>
          </p>
          <p>
            <span>事件标签:</span>
            <span>{info.eventLabel ? info.eventLabel.join(',') : '-'} </span>
          </p>
          <p>
            <span>主体名称:</span>
            <span>{info.name ? info.name : '-'} </span>
          </p>
          <div>
            <span>重要性:</span>
            {info.importantLevel != undefined || info.importantLevel != null ? (
              <Rate disabled={true} value={Number(info.importantLevel)} count={3} style={{ color: colors.echart[1], fontSize: '16px' }} />
            ) : (
              '-'
            )}
          </div>
        </div>
        <div style={{ marginTop: '17px' }}>
          {/* 展示后台返回的html */}
          <div dangerouslySetInnerHTML={{ __html: info.content }} />
        </div>
      </div>
    ) : (
      <div className={styles.newsInfo} style={{ maxHeight: currentHeight, overflow: 'auto' }}>
        <div style={{ marginBottom: '5px' }}>
          <b>{info.noticeTitle || '-'}</b>
        </div>
        <div>
          <p>
            <span>日期:</span>
            <span>{info.noticeDate || '-'} </span>
          </p>
          <p>
            <span>类型:</span>
            <span>{info.noticeType ? info.noticeType : '-'} </span>
          </p>
          <p>
            <span>发行主体:</span>
            <span>{info.name ? info.name : '-'} </span>
          </p>
          {info.url ? (
            <div>
              <span>附件:</span>
              <a href={info.url ? info.url : '#'} target='_blank'>
                {'附件'}{' '}
              </a>
            </div>
          ) : (
            <div>
              <span>附件: -</span>
            </div>
          )}
        </div>
      </div>
    );
  };

  render() {
    const { type } = this.props;
    return (
      <div className={styles.newsDetail}>
        <FirstHeaderC title={type == 'news' ? '新闻详情' : '公告详情'} />
        <Row gutter={20}>
          <Col span={16}>
            <SecondHeaderC title={'详情'} />
            {this.showInfo()}
          </Col>
          <Col span={8}>
            <SecondHeaderC title={'相关持仓'} />
            {this.showTable()}
          </Col>
        </Row>
      </div>
    );
  }
}
